package com.chengh.vhr.exception;

import com.chengh.vhr.common.myEnum.ErrorCodeEnum;
import com.chengh.vhr.model.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常管理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 针对sql异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public RespBean sqlException(SQLException e) {
        e.printStackTrace();
        if(e instanceof SQLIntegrityConstraintViolationException) {
            return RespBean.error("该数据有关联的数据,操作失败!");
        }
        return RespBean.error("以扑捉到位置异常,请处理!");
    }

    @ExceptionHandler(MyException.class)
    public RespBean myException(MyException myException) {
        myException.printStackTrace();
        log.error("错误: ",myException);
        return RespBean.error(myException.getCode(), myException.getMsg());
    }

    /**
     * 处理没有指定的异常,这样程序即使发现异常,也能在这儿做处理,前端页面友好
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public RespBean handleException(Throwable throwable) {
        log.error("错误: ",throwable);
        return RespBean.error(ErrorCodeEnum.UNKNOW_EXCEPTION.getCode(), ErrorCodeEnum.UNKNOW_EXCEPTION.getMsg() );
    }

}
